package com.qpx.studentservice.web;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qpx.studentservice.annotation.Log;
import com.qpx.studentservice.dto.SutdentDto;
import com.qpx.studentservice.entity.THouse;
import com.qpx.studentservice.entity.TStudent;
import com.qpx.studentservice.service.ITHouseService;
import com.qpx.studentservice.service.ITStudentService;
import com.qpx.studentservice.vo.ResultEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Mht
 * @since 2020-02-10
 */
@RestController
@RequestMapping("/tStudent")
public class TStudentController {


    @Autowired
    ITStudentService itStudentService;


    @Autowired
    ITHouseService itHouseService;

    @RequestMapping(value = "/page/list",method = RequestMethod.GET)
    public ResultEntity  selectStudentList(SutdentDto sutdentDto){
        PageHelper.startPage(sutdentDto.getPageNo(),sutdentDto.getPageSize());
        TStudent tStudent = new TStudent();
        BeanUtils.copyProperties(sutdentDto,tStudent);
        List<TStudent> tStudents = itStudentService.selectStudentList(tStudent);
        PageInfo<TStudent> page = new PageInfo<TStudent>(tStudents);
        return  ResultEntity.ok(page);
    }


    @Log("修改或者新增学生信息和成绩")
    @RequestMapping(value = "/saveOrUpdate",method = RequestMethod.POST)
    public ResultEntity  saveOrUpdate(@RequestBody SutdentDto sutdentDto){

        TStudent tStudent1 = new TStudent();
        BeanUtils.copyProperties(sutdentDto,tStudent1);
        if (sutdentDto.getId()==null){
            Wrapper<TStudent> ts = new EntityWrapper<>();
            ts.eq("stu_no",sutdentDto.getStuNo());
            TStudent tStudent = itStudentService.selectOne(ts);
            if (tStudent!=null){
                return ResultEntity.error("学号已经存在");
            }
            itStudentService.insert(tStudent1);
        }else {
            itStudentService.updateById(tStudent1);
        }

        itStudentService.save(sutdentDto,tStudent1);
        return ResultEntity.ok();
    }


    @Log("删除学生信息和成绩")
    @RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    public ResultEntity  delete(Integer stuID){

        itStudentService.delete(stuID);
        return ResultEntity.ok();
    }


}
